<?php

namespace App\Http\Controllers\User;

use App\Events\Order;
use App\Http\Controllers\BaseController;
use App\Models\Member;
use App\Models\MemberItem;
use App\Models\MemberOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Yansongda\Pay\Pay;

class MemberController extends BaseController
{
    public function index()
    {
        $data = Member::query()->with('items')->get();


        return $this->success($data);
    }

    // 获取会员详情
    public function show(Request $request)
    {
        $params = $this->validate($request,[
           'member_id' => 'required|integer'
        ]);

        $data = Member::query()->where('id',$params['member_id'])->first();


        return $this->success($data);
    }

    public function list(Request $request)
    {

        $param = $this->validate($request,[
            'status' => 'in:1,2'
        ]);

        $user_id = auth('api')->id();

        $query =  MemberOrder::query();

        if (isset($param['status'])){
            $query->where('status',$param['status']);
        }

        $data = $query->where('user_id',$user_id)
                    ->orderByDesc('id')
                    ->simplePaginate();

        return $this->success($data);
    }

    public function store(Request $request)
    {
        $param = $this->validate($request,[
             'member_item_id' => 'required',
             'platform' => 'required|in:1,2,3',
             'pay_method' => 'required|in:1,2'
        ]);

        $member = MemberItem::query()->with('member')->where('id',$param['member_item_id'])->first();

        if (empty($member)){
            return $this->success($member);
        }

        $user = auth('api')->user();
        $memberOrder = MemberOrder::query()->create([
            'user_id' =>  $user['id'],
            'member_id' => $member->member_id,
            'name' => $member->member->name,
            'price' => $member->price,
            'trade_no' => getTradeNo(),
            'month' => $member->valid_time,
            'cover' => $member->member->cover,
            'platform' => $param['platform'],
            'pay_method' =>  $param['pay_method']
        ]);

        if (!$memberOrder->getKey()){
            return  $this->error('下单失败');
        }


        $config = config('pay');
        switch ($param['pay_method']){
            case 1 :
                $config['wechat']['default']['notify_url'] = 'https://www.huashimu.com/api/user/member/notify';
                Pay::config($config);
                $order = [
                    'out_trade_no' => $memberOrder->trade_no,
                    'description' => '广告支付',
                    'amount' => [
                        'total' => (int)bcmul($memberOrder->price,'100'),
                    ],
                ];
                $payInfo = '';
                switch ($param['platform']){
                    case 1:
                        $payInfo =  Pay::wechat()->app($order);
                        break;
                    case 2 :
                        $order['payer']['openid'] = $user['wx_min_openid'];
                        $payInfo = Pay::wechat()->mini($order);
                        break;
                    case 3 :
                        $result = Pay::wechat()->scan($order);
                        $payInfo = ['code_url' => $result->code_url,'trade_no'=> $memberOrder->trade_no];
                        break;
                }

                return $this->success($payInfo);
            case 2 :
                $config['alipay']['default']['notify_url'] = 'https://www.huashimu.com/api/user/member/ali/notify';
                $config['alipay']['default']['return_url'] = 'http://www.xn--4pvs78ay6h.xn--fiqs8s/#/mine/memberCenter';
                Pay::config($config);

                if ($param['platform']==1){
                    $aliPay  = Pay::alipay()->app([
                        'out_trade_no' =>  $memberOrder->trade_no,
                        'total_amount' => $memberOrder->price,
                        'subject' => '会员购买',
                    ])->getBody()->getContents();
                }else{
                    $aliPay  = Pay::alipay()->web([
                        'out_trade_no' =>  $memberOrder->trade_no,
                        'total_amount' => $memberOrder->price,
                        'subject' => '会员购买',
                    ])->getBody()->getContents();
                }

                return  $this->success(['payInfo' => $aliPay]);
        }

    }

    public function notify()
    {
        $config = config('pay');
        $config['wechat']['default']['notify_url'] = 'https://www.huashimu.com/api/user/member/notify';
        Pay::config($config);

        $result = Pay::wechat()->callback()->toArray();

        if ($result && $result['event_type'] == 'TRANSACTION.SUCCESS'){
            $order = MemberOrder::query()
                    ->where('trade_no',$result['resource']['ciphertext']['out_trade_no'])
                    ->first();

            if ($order && $order->status==1){
                $trade_time = date('Y-m-d H:i:s',strtotime($result['resource']['ciphertext']['success_time']));
                event(new Order($order->user_id));
                MemberOrder::query()->where('id',$order->id)->update([
                    'status' => 2,
                    'pay_time' => $trade_time
                ]);

                $member =  DB::table('user_members')
                    ->where('user_id',$order->user_id)
                    ->where('member_id',$order->member_id)
                    ->first();

                if (empty($member)){
                    DB::table('user_members')
                         ->insert([
                             'user_id' => $order->user_id,
                             'member_id' => $order->member_id,
                             'end_time' => strtotime('+'.$order->month.' month')
                         ]);
                }else{
                    if ($member->end_time>time()){
                        $end_time = strtotime(date('Y-m-d H:i:s',$member->end_time).' +'.$order->month.' month');
                    }else{
                        $end_time = strtotime('+'.$order->month.' month');
                    }

                    DB::table('user_members')->where('id',$member->id)->update([
                        'end_time' => $end_time,
                    ]);
                }

                DB::table('users')
                    ->where('id',$order->user_id)
                    ->update(['member_id' => $order->member_id]);

                event(new \App\Events\Member($order->user_id));

                return Pay::wechat()->success();
            }

        }
    }


    public function aliNotify()
    {
        $config = config('pay');
        Pay::config($config);

        $result = Pay::alipay()->callback()->toArray();
        if ($result['trade_status']==='TRADE_SUCCESS'){
            $order = MemberOrder::query()->where('trade_no',$result['out_trade_no'])->first();
            if ($order && $order->status==1){

                event(new Order($order->user_id));
                MemberOrder::query()->where('id',$order->id)->update([
                    'status' => 2,
                    'pay_time' => $result['gmt_payment']
                ]);

                $member =  DB::table('user_members')
                    ->where('user_id',$order->user_id)
                    ->where('member_id',$order->member_id)
                    ->first();

                if (empty($member)){
                    DB::table('user_members')
                        ->insert([
                            'user_id' => $order->user_id,
                            'member_id' => $order->member_id,
                            'end_time' => strtotime('+'.$order->month.' month')
                        ]);
                }else{
                    if ($member->end_time>time()){
                        $end_time = strtotime(date('Y-m-d H:i:s',$member->end_time).' +'.$order->month.' month');
                    }else{
                        $end_time = strtotime('+'.$order->month.' month');
                    }

                    DB::table('user_members')->where('id',$member->id)->update([
                        'end_time' => $end_time,
                    ]);
                }

                DB::table('users')
                    ->where('id',$order->user_id)
                    ->update(['member_id' => $order->member_id]);

                event(new \App\Events\Member($order->user_id));


                return Pay::alipay()->success();
            }

        }

    }
}
